<?php

namespace app\api\controller;

class Auth extends Basic
{
    protected $postInfo = [];
    protected $user = [];
    protected $userid = 0;
    protected $table;
    protected $userInfo = [];

    public function __construct()
    {
        parent::__construct();
        $this->initUserinfo();
    }

    private function initUserinfo()
    {
        $info = $this->getUserInfoByToken();
        if (!empty($info)) {
            if ($info['table'] == 'member') {
                $where = ['memberid' => $info['userid']];
                $table = 'member';
                $this->role = 1;
            } else {
                $where = ['coachid' => $info['userid']];
                $table = 'coach';
                $this->role = 2;
            }

            $res = $this->findTable($table, ['where' => $where]);
            if ($info['table'] == 'member') {
                unset($res['memberpassword']);
                $username = $res['membertruename'];
            } else {
                unset($res['coachpassword']);
                $username = $res['coachtruename'];
            }

            $this->userid = $info['userid'];
            $this->user = $res;
            $this->table = $table;

            if (((time() - $info['addtime']) / 86400) > 15 || (in_array($res['status'], [0,2,3]) && $info['table'] == 'member') || (in_array($res['status'], [0,4]) && $info['table'] == 'coach')) {
                $update = [
                    'where' => [
                        'table' => $this->table,
                        'status' => 1,
                        'userid' => $this->userid,
                    ],
                    'data' => ['status' => 0],
                ];

                $this->updateTable('user_login', $update);
                $this->initreturn('登录超时，请重新登录');
            }

            $active = $this->findTable('user_active', ['where' => [
                ['userid', '=', $this->userid],
                ['table', '=', $this->table],
                ['addtime', 'between', [strtotime(date('Y-m-d')), time()]],
            ], 'field' => 'id']);

            if(empty($active)) {
                $this->insertTable('user_active', [
                    'userid' => $this->userid,
                    'table' => $this->table,
                    'username' => $username,
                    'targetdate' => date('Y-m-d H:i:s'),
                ]);
            }

        } else {
            $this->initreturn('登录超时，请重新登录');
        }
    }

    protected function initreturn($msg)
    {
        $execTime = $this->microtime_float() - $this->begin;
        $result = [
            'code' => 999,
            'message' => $msg,
            'time' => $execTime ? $execTime : time(),
            'result' => [],
        ];
        exit(json_encode($result, JSON_UNESCAPED_UNICODE));
    }


    public function setOrderTime($orderinfo, $type = 0)
    {
        $orderid = $orderinfo['orderid'];
        $where = ['orderid' => $orderid, 'status' => 1];
        $info = $this->findTable('order_timing', ['where' => $where]);
        if (empty($info) && $type == 0) {
            $data = [
                'endtime' => strtotime('+30 days'),
                'orderid' => $orderid
            ];
            $price = bcdiv($orderinfo['price'], 2, 2);
            $param = [
                'status' => 1,
                'coachid' => $orderinfo['coachid'],
                'memberid' => $orderinfo['memberid'],
                'amount' => $price,
                'type' => 1,
                'source' => 'order',
                'sourceid' => $orderinfo['orderid'],
                'describe' => '首款到账：' . $price,
            ];

            $fdata = [
                'coachid' => $orderinfo['coachid'],
                'money' => $price,
                'type' => 1,
            ];

            $where = ['coachid' => $orderinfo['coachid'], 'isdel' => 0, 'status' => 1];
            $coach_amount = $this->findTable('coach_amount', ['where' => $where]);

            if (empty($coach_amount)) {
                $amoundata = [
                    'coachid' => $orderinfo['coachid'],
                    'totalamount' => $price,
                ];
                $arow = $this->insertTable('coach_amount', $amoundata);
            } else {
                $amoundata = [
                    'data' => [
                        'totalamount' => bcadd($coach_amount['totalamount'], $price, 2),
                        'revision' => $coach_amount['revision'] + 1,
                    ],
                    'where' => [
                        'id' => $coach_amount['id'],
                        'revision' => $coach_amount['revision'],
                    ]
                ];
                $arow = $this->updateTable('coach_amount', $amoundata);
            }

            $finance = $this->insertTable('finance', $fdata);
            $ans = $this->insertTable('order_timing', $data);
            $row = $this->insertTable('performance', $param);
            // 提交事务
            if ($ans && $row && $finance && $arow) {
                return true;
            } else {
                return false;
            }
        } else if (!empty($info) && $type == 1) {
            $data = [
                'data' => [
                    'endtime' => strtotime('+30 days'),
                    'revision' => time(),
                    'status' => 3,
                ],
                'where' => [
                    'id' => $info['id'],
                    'revision' => $info['revision'],
                ]
            ];
            $ans = $this->updateTable('order_timing', $data);
            if ($ans) {
                return true;
            } else {
                return false;
            }
        }
    }
}
